<template>
  <div class="create_box">
    <el-popover placement="right" width="260" trigger="click" :visible="popoverVisible">
      <div v-loading="tagsLoading">
        <div class="" v-if="isCreateTagsBoxShow">
          <div class="tags_header">
            <div class="title">创建标签</div>
            <el-icon @click="create_closeClick"><Close /></el-icon>
            <!-- <i class="el-icon-close" @click="create_closeClick"></i> -->
          </div>
          <div class="input_create">
            <el-input placeholder="请输入内容" v-model="inputCreate_value"> </el-input>
          </div>
          <div class="create_Box createBtn">
            <el-button type="primary" @click="create_confirmClick">创建标签</el-button>
          </div>
        </div>
        <div v-else>
          <div class="tags_header">
            <div class="title">选择标签(共{{ requestStr.total }}个)</div>
            <el-icon @click="tags_closeClick"><Close /></el-icon>
            <!-- <i class="el-icon-close" @click="tags_closeClick"></i> -->
          </div>
          <div class="tags_search">
            <el-input placeholder="请输入内容" prefix-icon="el-icon-search" class="" v-model="inputSearch" @input="allTags_inputSearch"> </el-input>
          </div>
          <div class="tabs_box">
            <div class="tabs_item" v-for="(item, index) in AllTagsList" :key="index" @click="select_TagsClick(item, index)">
              <div>
                <svg-icon icon-class="tags1"></svg-icon>
                <span>{{ item.labelName }}</span>
              </div>
              <div v-if="item.isChecked">
                <el-icon class="iconBg"><Check /></el-icon>
                <!-- <i class="el-icon-check iconBg"></i> -->
              </div>
            </div>
            <el-pagination
              class="pagination"
              v-model:current-page="requestStr.page"
              @current-change="handleCurrentChange"
              :page-size="requestStr.size"
              layout="prev, pager, next"
              :total="requestStr.total"
            >
            </el-pagination>
          </div>
          <div class="btn_box create_Box">
            <div class="create_tags" @click="create_openClick">创建标签</div>
            <el-button type="primary" @click="tags_confirmClick">确 定</el-button>
          </div>
        </div>
      </div>
      <template #reference>
        <el-button size="small" class="create_tags_btn" type="primary" :icon="Plus" @click="openTagsDialog()">
          <span class="create_text">添加标签</span>
        </el-button>
      </template>
    </el-popover>
  </div>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue';
import { ApiPerfilesUserLabel, ApiPerQuerySelect, ApiPerLabelCreate, ApiPerRecordCreate } from '@/api/personDoc/personDocApi';

const emit: any = defineEmits(['refreshData']);

const tagsLoading = ref(false);
const popoverVisible = ref(false);

const isCreateTagsBoxShow = ref(false);
const inputSearch = ref('');
const inputCreate_value = ref('');
const AllTagsList = ref([]);
const requestStr = ref({
  page: 1,
  size: 8,
  total: 0
});
const oldContrast_TagsList = ref([]); //用于对比
const my_TagsList = ref([]);

const props = defineProps({
  //用于接收父组件通过ref传递过来的文件对象
  parentObj: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

/** 打开标签对话框 */
const openTagsDialog = async () => {
  popoverVisible.value = true;
  requestStr.value.page = 1;
  isCreateTagsBoxShow.value = false;
  await apiFilesLabelRecordQuerySelect(props.parentObj);
  await apiFilesUserLabelQuery();
};

// 查询标签记录已添加的文件
const apiFilesLabelRecordQuerySelect = async (row) => {
  let oParam = {
    fileId: row.id,
    fileType: row.libraryType,
    labelType: 'user'
  };
  await ApiPerQuerySelect(oParam).then((res) => {
    console.log('🚀 ~ awaitApiPerQuerySelect ~ res查询标签记录已添加的文件:', res);
    if (res) {
      // oldContrast_TagsList.value = JSON.parse(JSON.stringify(res.data.rows));
      oldContrast_TagsList.value = JSON.parse(JSON.stringify(res.data));
      my_TagsList.value = res.data;
    }
  });
};

// 分页查询全部我的标签
const apiFilesUserLabelQuery = async () => {
  tagsLoading.value = true;
  let oParam = {
    page: requestStr.value.page - 1,
    size: requestStr.value.size,
    labelName: inputSearch.value
  };
  await ApiPerfilesUserLabel(oParam)
    .then((res) => {
      console.log('🚀 ~ apiFilesUserLabelQuery ~ res:', res);

      tagsLoading.value = false;
      res.data.rows.forEach((item) => {
        let index = my_TagsList.value.findIndex((val) => val.labelId == item.id);
        if (index !== -1) {
          item.isChecked = true;
        } else {
          item.isChecked = false;
        }
        // this.AllTagsList.push(item)
      });

      AllTagsList.value = res.data.rows;

      requestStr.value.total = res.data.total;
    })
    .catch((err) => {
      tagsLoading.value = false;
    });
};
/**搜索 */
const allTags_inputSearch = () => {
  requestStr.value.page = 1;
  apiFilesUserLabelQuery();
};

/**确定按钮 */
const tags_confirmClick = () => {
  const { delArr, addArr } = compareArrayDiff(my_TagsList.value, oldContrast_TagsList.value);
  console.log(my_TagsList.value, 'this.my_TagsList');
  console.log(oldContrast_TagsList.value, 'this.oldContrast_TagsList');
  console.log(delArr, 'delArr');
  console.log(addArr, 'addArr');

  let delIds = delArr.map((item) => item.labelId);
  let addIds = addArr.map((item) => item.labelId);
  if (delArr.length == 0 && addArr.length == 0) {
    popoverVisible.value = false;
    return false;
  }

  let oParam = {
    fileId: props.parentObj.id,
    fileType: props.parentObj.libraryType,
    labelId: addIds,
    removeLabelId: delIds,
    labelType: 'user'
  };
  console.log('🚀 ~ oParam:确定按钮', oParam);

  ApiPerRecordCreate(oParam).then((res) => {
    emit('refreshData');
    ElMessage.success('操作成功');
    popoverVisible.value = false;
  });
};

/**选择标签 */
const select_TagsClick = (row, i) => {
  AllTagsList.value.forEach((item, index) => {
    if (item.id == row.id) {
      if (item.isChecked) {
        //删除
        item.isChecked = false;
        let index = my_TagsList.value.findIndex((val) => val.labelId == row.id);
        if (index !== -1) {
          my_TagsList.value.splice(index, 1);
        }
      } else {
        //添加
        item.isChecked = true;
        item.labelId = item.id;
        my_TagsList.value.push(item);
      }
    }
  });
};

/**打开创建 */
const create_openClick = () => {
  inputCreate_value.value = '';
  isCreateTagsBoxShow.value = true;
};
/**关闭选择标签 */
const tags_closeClick = () => {
  console.log('🚀 ~ tags_closeClick:');
  popoverVisible.value = false;
  inputSearch.value = '';
};

/**创建标签 */
const create_confirmClick = () => {
  if (inputCreate_value.value == '') {
    ElMessage.warning('标签不能为空');
    return;
  }
  tagsLoading.value = true;
  let oParam = {
    labelName: inputCreate_value.value
  };
  ApiPerLabelCreate(oParam)
    .then((res) => {
      tagsLoading.value = false;
      apiFilesUserLabelQuery();
      create_closeClick();
    })
    .catch((err) => {
      tagsLoading.value = false;
    });
};

/**关闭创建 */
const create_closeClick = () => {
  isCreateTagsBoxShow.value = false;
};

/**分页 */
const handleCurrentChange = (val) => {
  requestStr.value.page = val;
  apiFilesUserLabelQuery();
};

/**数组对比---新 旧 数组对不  筛选 哪些是删除的  哪些是新增的 */
const compareArrayDiff = (newArr, oldArr) => {
  const tNewArr = newArr;
  const tOldArr = oldArr;
  const totalArr = [...new Set(tNewArr.concat(tOldArr))];
  // 新数组 与 全数组比较差异，得到新数组 删掉的项(新数组中不存在，而总数组存在，则是新数组删掉的)
  const delArr = [];
  totalArr.forEach((item: any) => {
    if (tNewArr.findIndex((val: any) => val.labelId == item.labelId) == -1) delArr.push(item);
  });
  // 旧数组 与 全数组比较差异，得到新数组 增加的项(旧数组中不存在，而总数组存在，则是新数组增加的)
  const addArr = [];
  totalArr.forEach((item: any) => {
    if (tOldArr.findIndex((val: any) => val.labelId == item.labelId) == -1) addArr.push(item);
    // if (!tOldArr.includes(item)) addArr.push(item);
  });

  return {
    delArr,
    addArr
  };
};

onMounted(() => {
  // console.log(props.parentObj, '用于接收父组件通过ref传递过来的文件对象');
});
</script>

<style scoped lang="scss">
.tags_header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  i {
    cursor: pointer;
  }
}
.tags_search {
  margin: 8px 0;
  :deep(.el-input__inner) {
    border-radius: 16px;
  }
}
.tabs_box {
  .tabs_item {
    padding: 6px 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    .iconBg {
      color: #6698ff;
    }
    svg {
      color: #6698ff;
    }
    &:hover {
      background-color: #eee;
    }
  }
}
.pagination {
  :deep(.el-pager li) {
    min-width: 22px;
  }

  &:deep(button) {
    min-width: 30px;
  }

  :deep(.el-pager li.active) {
    color: #6698ff;
  }
}
.btn_box {
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .create_tags {
    cursor: pointer;
    &:hover {
      color: #6698ff;
    }
  }
}
.create_Box {
  :deep(.el-button--text:hover) {
    color: #6698ff;
  }
  :deep(.el-button--primary) {
    background-color: #6698ff;
    border-color: #6698ff;
  }
  :deep(.el-button--primary:focus) {
    box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  }
  :deep(.el-button--primary:hover) {
    box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  }
}
.createBtn {
  display: flex;
  justify-content: flex-end;
}
.input_create {
  margin: 8px 0;
}
</style>
